//
//  ShowBigImageViewController.m
//  XiangMuB
//
//  Created by lanou3g on 16/8/18.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "ShowBigImageViewController.h"

#import <Photos/Photos.h>
#import "BigImageCollectionViewCell.h"
#import "PhotoTool.h"
#import "MBProgressHUD.h"
#import "PhotoModel.h"

@interface ShowBigImageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>

@property (strong, nonatomic) UICollectionView *collectionView;

@property (strong, nonatomic) NSMutableArray<PHAsset *> *arrayDataSource;
@property (strong, nonatomic) UIButton *rightNaivigationButton;

@property (strong, nonatomic) UIView *bottomView;
@property (strong, nonatomic) UIButton *originalPhotoButton;
@property (strong, nonatomic) UIButton *doneButton;

//双击
@property (strong, nonatomic) UIScrollView *selectScrollview;
@property (assign, nonatomic) NSInteger currentPage;

@property (strong, nonatomic) UILabel *labelPhotoBytes;

@end

@implementation ShowBigImageViewController

- (NSMutableArray<PHAsset *> *)arrayDataSource{
    
    if (_arrayDataSource == nil) {
        _arrayDataSource = [NSMutableArray array];
    }
    return _arrayDataSource;
}

- (UICollectionView *)collectionView{
    
    if (_collectionView == nil) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 30;
        layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
        layout.itemSize = self.view.bounds.size;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(-30/2, 0, [UIScreen mainScreen].bounds.size.width + 30, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:layout];
        
        _collectionView.backgroundColor = [UIColor blackColor];
        [_collectionView registerClass:[BigImageCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        
    }
    
    return _collectionView;
}

- (void)viewDidLoad {
    
   
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupNavigation];
    [self sortAsset];
    [self.view addSubview:self.collectionView];
    
    [self setupBottomViews];
    [self changeButtonDoneTitle];
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    if (self.shouldReverseAssets) {
        [self.collectionView setContentOffset:CGPointMake((self.assets.count - self.selectIndex - 1) * ([UIScreen mainScreen].bounds.size.width + 30), 0)];
    } else {
        
        [self.collectionView setContentOffset:CGPointMake(self.selectIndex * ([UIScreen mainScreen].bounds.size.width + 30), 0)];
    }
    
    [self changeNaviagationRightBarStatus];
    
}

- (void)changeNaviagationRightBarStatus{
    
    if ([self isHaveCurrentImage]) {
        
        self.rightNaivigationButton.selected = YES;
    } else {
        
        self.rightNaivigationButton.selected = NO;
    }
    
}

- (void)setupNavigation{
    
    UIImage *navigationBack = [UIImage imageNamed:@"navBackBtn@2x"];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[navigationBack imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backButton)];
    
    self.rightNaivigationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightNaivigationButton.frame = CGRectMake(0, 0, 25, 25);
    UIImage *nalmal = [UIImage imageNamed:@"btn_circle@2x"];
    UIImage *selectImage = [UIImage imageNamed:@"btn_selected"];
    [self.rightNaivigationButton setBackgroundImage:nalmal forState:UIControlStateNormal];
    [self.rightNaivigationButton setBackgroundImage:selectImage forState:UIControlStateSelected];
    
    [self.rightNaivigationButton addTarget:self action:@selector(rightNavigationAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightNaivigationButton];
    
    
}

- (void)sortAsset{
    
    if (self.shouldReverseAssets) {
        
        NSEnumerator *enumerator = [self.assets reverseObjectEnumerator];
        id obj;
        while (obj = [enumerator nextObject]) {
            [self.arrayDataSource addObject:obj];
        }
        
        self.currentPage = self.arrayDataSource.count - self.selectIndex;
        
    } else {
        
        [self.arrayDataSource addObjectsFromArray:self.assets];
        self.currentPage = self.selectIndex + 1;
    }
    
    self.title = [NSString stringWithFormat:@"%ld/%ld",(long)self.currentPage,(unsigned long)self.arrayDataSource.count];
    
}

- (void)setupBottomViews{
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 44, self.view.frame.size.width, 44)];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    
    self.originalPhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.originalPhotoButton.frame = CGRectMake(12, 7, 60, 30);
    [self.originalPhotoButton setTitle:@"原图" forState:UIControlStateNormal];
    self.originalPhotoButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.originalPhotoButton setTitleColor:[UIColor colorWithRed:80/255.0 green:180/255.0 blue:234/255.0 alpha:1.0] forState:UIControlStateNormal];
    
    [self.originalPhotoButton setTitleColor:[UIColor colorWithRed:80/255.0 green:180/255.0 blue:234/255.0 alpha:1.0] forState:UIControlStateSelected];
    
    UIImage *narmalImage = [UIImage imageNamed:@"btn_original_circle"];
    UIImage *selectImage = [UIImage imageNamed:@"btn_selected"];
    
    [self.originalPhotoButton setImage:narmalImage forState:UIControlStateNormal];
    [self.originalPhotoButton setImage:selectImage forState:UIControlStateSelected];
    [self.originalPhotoButton setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
    [self.originalPhotoButton addTarget:self action:@selector(originalButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.originalPhotoButton.selected = self.isSelectOriginalPhoto;
    
    if (self.arraySelectPhotos.count > 0) {
        [self getPhotoBytes];
    }
    
    [self.bottomView addSubview:self.originalPhotoButton];
    
    self.labelPhotoBytes = [[UILabel alloc] initWithFrame:CGRectMake(75, 7, 80, 30)];
    self.labelPhotoBytes.font = [UIFont systemFontOfSize:15];
    self.labelPhotoBytes.textColor = [UIColor colorWithRed:80/255.0 green:180/255.0 blue:234/255.0 alpha:1.0];
    [self.bottomView addSubview:self.labelPhotoBytes];
    
    self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.doneButton.frame = CGRectMake(self.view.frame.size.width - 82, 7, 70, 30);
    [self.doneButton setTitle:@"确定" forState:UIControlStateNormal];
    self.doneButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.doneButton.layer.masksToBounds = YES;
    self.doneButton.layer.cornerRadius = 3.0f;
    
    [self.doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.doneButton setBackgroundColor:[UIColor colorWithRed:80/255.0 green:180/255.0 blue:234/255.0 alpha:1.0]];
    [self.doneButton addTarget:self action:@selector(doneButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.doneButton];
    
    [self.view addSubview:self.bottomView];
    
}

- (void)originalButtonAction:(UIButton *)button{
    
   
    self.isSelectOriginalPhoto = button.selected = !button.selected;
    
    if (button.selected) {
        if (![self isHaveCurrentImage]) {
            [self rightNavigationAction:self.rightNaivigationButton];
        } else {
            
            [self getPhotoBytes];
        }
    } else {
        
        self.labelPhotoBytes.text = nil;
    }
}

- (void)doneButtonAction:(UIButton *)button{
    
    if (self.arraySelectPhotos.count == 0) {
        
        PHAsset *asset = self.arrayDataSource[self.currentPage - 1];
        
        if (![[PhotoTool sharePhotoTool] judgeAssetisInLocalAblum:asset]) {
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            hud.label.text = @"图片加载中，请稍等";
            [hud hideAnimated:YES afterDelay:2];
          
            
            return;
            
        }
        
        PhotoModel *model = [[PhotoModel alloc] init];
        model.asset = asset;
        model.localIdentifier = asset.localIdentifier;
        [self.arraySelectPhotos addObject:model];

        
    }
    
    NSLog(@"%@",self.arraySelectPhotos);
    if (self.btnDoneBlock) {
        self.btnDoneBlock(self.arraySelectPhotos,self.isSelectOriginalPhoto);
    }
    
}


- (void)backButton{
    
    if (self.onSelectedPhotos) {
        self.onSelectedPhotos(self.arraySelectPhotos,self.isSelectOriginalPhoto);
    }
    
    if (self.isPresent) {
        
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    } else {
        
        self.collectionView.backgroundColor = [UIColor clearColor];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)rightNavigationAction:(UIButton *)button{
    
    if (self.arraySelectPhotos.count >= self.maxSelectCount && button.selected == NO) {
        
        [self getPhotoBytes];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = [NSString stringWithFormat:@"最多只能选择%ld张图片",(long)self.maxSelectCount];
        [hud hideAnimated:YES afterDelay:2];
        return;
        
    }
    
    PHAsset *asset = self.arrayDataSource[self.currentPage - 1];
    if (![self isHaveCurrentImage]) {
        
        CAKeyframeAnimation *animation = [self getButtonStatusChangedAnimation];
        [button.layer addAnimation:animation forKey:nil];
        
        if (![[PhotoTool sharePhotoTool] judgeAssetisInLocalAblum:asset]) {
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.label.text = @"图片加载中，请稍等";
            [hud hideAnimated:YES afterDelay:2];
            return;
            
        }
        
        PhotoModel *model = [[PhotoModel alloc] init];
        model.asset = asset;
        model.localIdentifier = asset.localIdentifier;
        [self.arraySelectPhotos addObject:model];
        
        
    } else {
        
        [self removeCurrentImage];
        
    }
    
    button.selected = !button.selected;
    [self getPhotoBytes];
    [self changeButtonDoneTitle];
    
    
}

- (void)removeCurrentImage{
    
    PHAsset *asset = self.arrayDataSource[self.currentPage - 1];
    for (PhotoModel *model in self.arraySelectPhotos) {
        
        if ([model.localIdentifier isEqualToString:asset.localIdentifier]) {
            [self.arraySelectPhotos removeObject:model];
            break;
        }
        
    }
}

- (BOOL)isHaveCurrentImage{
    
    PHAsset *asset = self.arrayDataSource[self.currentPage - 1];
    for (PhotoModel *model in self.arraySelectPhotos) {
        
        if ([model.localIdentifier isEqualToString:asset.localIdentifier]) {
            return YES;
        }
        
    }
    
    return NO;
    
}

- (void)changeButtonDoneTitle{
    
    if (self.arraySelectPhotos.count > 0) {
        
        [self.doneButton setTitle:[NSString stringWithFormat:@"确定(%ld)",(unsigned long)self.arraySelectPhotos.count] forState:UIControlStateNormal];
        
    } else {
        [self.doneButton setTitle:@"确定" forState:UIControlStateNormal];
    }
    
}

- (void)getPhotoBytes{
    
    if (!self.isSelectOriginalPhoto) {
        return;
    }
    
    if (self.arraySelectPhotos.count > 0) {
        
        __weak typeof(self) weakself = self;
        [[PhotoTool sharePhotoTool] getPhotoBytesWithArray:self.arraySelectPhotos completion:^(NSString *photosBytes) {
           
            weakself.labelPhotoBytes.text = [NSString stringWithFormat:@"(%@)",photosBytes];
            
        }];
        
    } else {
        self.labelPhotoBytes.text = nil;
    }
    
}


#pragma mark UICollectionDatasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.arrayDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifierCell = @"cell";
    
    BigImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierCell forIndexPath:indexPath];
    
    PHAsset *asset = self.arrayDataSource[indexPath.row];
    cell.assets = asset;
    
    __weak typeof(self) weakself = self;
    cell.singleTapCallBack = ^(){
        
        if (weakself.navigationController.navigationBar.isHidden) {
            
            [weakself showNavigationBarAndBottomView];
            
        } else {
            
            [weakself hideNavigationBarBottomView];
            
        }
        
    };
    
    
    return cell;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView == (UIScrollView *)self.collectionView) {
        
        CGFloat page = scrollView.contentOffset.x/([UIScreen mainScreen].bounds.size.width + 30);
        
        NSString *string = [NSString stringWithFormat:@"%.0f",page];
        
        self.currentPage = string.integerValue + 1;
        self.title = [NSString stringWithFormat:@"%ld/%ld",(long)self.currentPage,(unsigned long)self.arrayDataSource.count];
        
        [self changeNaviagationRightBarStatus];
        
    }
    
}


- (CAKeyframeAnimation *)getButtonStatusChangedAnimation{
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    
    animation.duration = 0.3;
    animation.removedOnCompletion = YES;
    animation.fillMode = kCAFillModeForwards;
    
    animation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.7, 0.7, 1.0)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    return animation;
    
}


- (void)showNavigationBarAndBottomView{
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    CGRect frame = self.bottomView.frame;
    frame.origin.y -= frame.size.height;
    [UIView animateWithDuration:0.3 animations:^{
       
        self.bottomView.frame = frame;
        
    }];
    
}

- (void)hideNavigationBarBottomView{
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    
    CGRect frame = self.bottomView.frame;
    frame.origin.y += frame.size.height;
    
    [UIView animateWithDuration:0.3 animations:^{
       
        self.bottomView.frame = frame;
        
    }];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
